<template>
  <div class="viewer-container" ref="viewContainerRef">
    <div
        v-if="!isLogin"
        style="width:100%;height: 100%;display: flex;align-items: center;justify-content:center;position: absolute;top: 0;left: 0;z-index: 2"
        v-loading="isLoading"
        element-loading-text="连接主设备中"
    >
      <el-button v-if="!isLogin" @click="handleConnect" size="large">连接到主设备</el-button>
    </div>
    <div class="ball"
         :style="{
          'transform':`translate(${ballLeft}px, ${ballTop}px)`
       }"
         v-show="touchBallFlag"
         @click="handleBallClick"
         @mousedown="handleBallMouseDown"
         @touchstart="handleBallMouseDown"
         @mousemove="mouseMove"
         @touchmove="mouseMove"

         @touchend="handleBallMouseUp"
         @mouseup="handleBallMouseUp"
    >
      <div class="inner-ball"></div>
    </div>
    <div id="screen"
         :style="{
            'z-index': isDown ? -1: 10
         }"
    >
    </div>
    <div class="mouse-op-cap-container"
         @mousemove="mouseMove"
         @touchmove="mouseMove"
         :style="{
            'z-index': isDown ? 10: -1
         }"
         @mouseup="handleBallMouseUp"
         @touchend="handleBallMouseUp">
    </div>
  </div>
  <el-dialog
      :model-value="!touchBallFlag && isLogin"
      top="500px"
      @close="showTouchBall = true"
  >
    <div style="width: 100%;display: flex;">
      <el-button @click="handleChangeRole" style="flex: 1">
        <svg t="1679560361420" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
             p-id="2771" width="25" height="25">
          <path
              d="M1011.2 787.2H448v-64h441.6l-32-51.2 51.2-38.4 102.4 153.6z m-486.4 204.8l57.6-25.6-25.6-51.2h454.4v-64H454.4l70.4 140.8z m-44.8-396.8c-217.6 0-390.4 166.4-409.6 377.6h-64c12.8-198.4 147.2-358.4 326.4-416C256 505.6 198.4 416 198.4 313.6c0-153.6 128-281.6 281.6-281.6 153.6 0 281.6 128 281.6 281.6 0 102.4-57.6 192-140.8 243.2 44.8 12.8 83.2 32 115.2 57.6l-44.8 44.8c-57.6-38.4-128-64-211.2-64z m0-57.6c121.6 0 217.6-96 217.6-217.6S601.6 96 480 96 262.4 192 262.4 313.6s96 224 217.6 224z"
              fill="" p-id="2772"></path>
        </svg>
        切换角色
      </el-button>
      <el-button @click="handleDisconnect" style="flex: 1">
        <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path
              d="M25.8927 16.0307L18.1145 8.2525C15.2506 5.38866 10.7031 5.29302 7.9572 8.0389C5.21132 10.7848 5.30696 15.3323 8.1708 18.1962L15.949 25.9744"
              stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
          <path
              d="M31.9161 22.0707L39.6943 29.8489C42.5581 32.7127 42.9291 37.1233 39.9079 40.0062C36.8867 42.8891 32.6144 42.6564 29.7506 39.7926L21.9724 32.0144"
              stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M21.2384 21.0759L17.3493 17.1868" stroke="#333" stroke-width="4" stroke-linecap="round"
                stroke-linejoin="round"/>
          <path d="M30.3131 30.1504L26.424 26.2613" stroke="#333" stroke-width="4" stroke-linecap="round"
                stroke-linejoin="round"/>
        </svg>
        断开连接
      </el-button>
      <el-button @click="emitKeyboard" style="flex: 1">
        <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path
              d="M42 7H6C4.89543 7 4 7.89543 4 9V37C4 38.1046 4.89543 39 6 39H42C43.1046 39 44 38.1046 44 37V9C44 7.89543 43.1046 7 42 7Z"
              fill="none" stroke="#333" stroke-width="4" stroke-linejoin="round"/>
          <path d="M12 19H14" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M21 19H23" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M29 19H36" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M12 28H36" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        调用键盘
      </el-button>
    </div>
  </el-dialog>


  <el-dialog
      v-model="dialogVisible"
      title="请选择登入角色"
      width="30%"
  >
    <el-select v-model="role" class="m-2" placeholder="Select" size="large">
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleConfirmRole"
        >Confirm</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script setup async>
import RFB from '@novnc/novnc/core/rfb';
import {computed, onMounted, ref, watch} from "vue";
import {
  beIP,
  wsAddr
} from '@/config/config';
import axios from 'axios'
import {ElMessage} from "element-plus";
import {ipcRenderer} from 'electron';
import _ from 'lodash'
// 5901 port
let hostWs = wsAddr;
let rfb = null;

const dialogVisible = ref(false);
const role = ref('share');
const isLogin = ref(false);
const isGetHostIP = ref(false);
const isLoading = ref(false);
const isChangingRole = ref(false);
const showTouchBall = ref(true);
const mouseOpCapRef = ref(null)
const touchBallFlag = computed(() => {
  return isLogin.value && showTouchBall.value
})
const options = [
  {
    value: 'share',
    label: 'Operator',
  },
  {
    value: 'view',
    label: 'View',
  }
]

onMounted(() => {
  isLoading.value = true
  connectVnc()
})


const ballTop = ref(0)
const ballLeft = ref(0)

function connectVnc() {
  if (isLogin.value) {
    handleDisconnect();
    const watchStop = watch(isLogin, (newVal, oldValue) => {
      if (newVal === false) {
        setTimeout(() => {
          login();
          watchStop();
        }, 500)
      }
    })
  } else {
    login();
  }
}

function login() {
  let PASSWORD;
  if (role.value === 'share') {
    PASSWORD = 'share';
  } else {
    PASSWORD = 'view'
  }
  console.log('hostWs:  ' + hostWs);
  rfb = new RFB(document.getElementById('screen'), hostWs, {
// 向vnc 传递的一些参数，比如说虚拟机的开机密码等
    credentials: {password: PASSWORD}
  });
  rfb.addEventListener('connect', connectedToServer);
  rfb.addEventListener('disconnect', disconnectedFromServer);
  rfb.scaleViewport = true; //scaleViewport指示是否应在本地扩展远程会话以使其适合其容器。禁用时，如果远程会话小于其容器，则它将居中，或者根据clipViewport它是否更大来处理。默认情况下禁用。
  rfb.resizeSession = true; //是一个boolean指示是否每当容器改变尺寸应被发送到调整远程会话的请求。默认情况下禁用
}

function connectedToServer() {
  isLoading.value = false
  ElMessage({
    message: '远程WS成功',
    type: "success"
  })
  isLogin.value = true;
}

function disconnectedFromServer(msg) {
  isLoading.value = false
  ElMessage({
    message: '远程WS连接断开',
    type: "error"
  })
  isLogin.value = false;
}

function handleDisconnect() {
  if (rfb !== null) {
    rfb._disconnect();
    rfb = null;
  }
}

function handleConnect() {
  dialogVisible.value = true;
}

function handleConfirmRole() {
  connectVnc();
  dialogVisible.value = false;
}

function handleChangeRole() {
  dialogVisible.value = true;
}

function emitKeyboard() {
  ipcRenderer.send('test');
}

const isDown = ref(false)
const isMoveBall = ref(false)


function handleBallMouseDown(e) {
  isDown.value = true
}

const mouseMove = _.throttle(e => {
  if (isDown.value === false) {
    return;
  }
  let x = 0
  let y = 0
  if (e.type === 'touchmove') {
    x = e.targetTouches[0].clientX
    y = e.targetTouches[0].clientY
  } else {
    x = e.clientX
    y = e.clientY
  }
  isMoveBall.value = true
  requestAnimationFrame(() => {
    ballTop.value = y - 25
    ballLeft.value = x - 25
  })
}, 0)

function handleBallMouseUp(e) {
  isDown.value = false
  setTimeout(() => {
    isMoveBall.value = false
  }, 10)
}


const handleBallClick = () => {
  if (isMoveBall.value === false) {
    showTouchBall.value = false
  }
}


</script>
<script>
export default {}
</script>
<style>
.viewer-container {
  position: relative;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}

.ball {
  position: absolute;
  width: 50px;
  height: 50px;
  background: #67c23a;
  opacity: 0.3;
  border-radius: 50%;
  z-index: 200;
  display: flex;
  align-items: center;
  justify-content: center;
}

.inner-ball {
  width: 30px;
  height: 30px;
  background-color: white;
  border-radius: 50%;
}

.mouse-op-cap-container {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0);
  position: absolute;
  left: 0;
  top: 0;
}

#screen {
  width: 100%;
  height: 100%;
}
</style>



